package com.geek.novel.adapter

import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.geek.novel.R
import com.geek.novel.common.BookDownloadEnum
import com.geek.novel.entity.BookDownload
import com.geek.novel.services.BookDownloadRepository
import com.geek.novel.services.BookRepository
import com.geek.novel.services.manager.BookDownloadManager
import com.geek.novel.ui.BookImageView
import com.geek.novel.utils.BookUtil.formatAuthorName
import com.geek.novel.utils.BookUtil.formatBookName

/**查询书籍缓存列表的适配器*/
class BookDownloadListAdapter(context: Activity, list: ArrayList<BookDownload>)
    : BaseRecyclerViewAdapter<BookDownloadListAdapter.ViewHolder, BookDownload>(context, list) {

    /**书籍的数据库操作接口*/
    private var bookService = BookRepository.getInstance()

    /**书籍缓存的数据库服务类*/
    private val bookDownloadRepository = BookDownloadRepository.getInstance()


    //定义内部类ViewHolder，并继承RecyclerView.ViewHolder传入View参数通常是Recycler View子项的最外层布局
    class ViewHolder(view: View, adapter: BaseRecyclerViewAdapter<BaseRecyclerViewHolder, Any>): BaseRecyclerViewHolder(view, adapter) {
        val imageView: BookImageView = view.findViewById(R.id.iv_download_book_image)
        val tvBookName: TextView = view.findViewById(R.id.tv_download_book_name)
        val tvBookOtherInfo: TextView = view.findViewById(R.id.tv_download_book_other_info)
        val tvBookLoading: TextView = view.findViewById(R.id.tv_download_book_loading)
        val btnBookDownload: LinearLayout = view.findViewById(R.id.layout_book_download)
        val iconBookDownload: ImageView = view.findViewById(R.id.iv_book_download_icon)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.listview_book_download, parent, false)
        return ViewHolder(view, this as BaseRecyclerViewAdapter<BaseRecyclerViewHolder, Any>)
    }


    /**绑定容器显示控件内容*/
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //设置书籍名称、书籍最新章节、书籍图片等等数据
        val bookDownload = list[position]

        val book = bookService.findBookByBookId(bookDownload.bookId) ?: return

        val bookName = book.bookName

        val imgId = book.imgId
        holder.imageView.setBookName(bookName)
        holder.imageView.loadBookImage(imgId)

        //书名
        holder.tvBookName.text = formatBookName(bookName)

        val authorName = formatAuthorName(book.authorName)

        //其他信息：作者 · 任务状态
        val otherInfo = StringBuilder()
        otherInfo.append(authorName)

        //任务状态
        val enum = BookDownloadEnum.find(bookDownload.status)
        if(enum != null){
            otherInfo.append(" · ")
            otherInfo.append("缓存状态")
            otherInfo.append("(").append(enum.typeName).append(")")
        }
        holder.tvBookOtherInfo.text = otherInfo.toString()

        //显示loading信息
        holder.tvBookLoading.text = bookDownload.loadingMessage
        if(bookDownload.error){
            holder.tvBookLoading.setTextColor(context.getColor(R.color.red))
        }else{
            holder.tvBookLoading.setTextColor(context.getColor(R.color.c999))
        }

        this.bindBookDownloadClickEvent(holder, position, bookDownload)

        //调用父类的方法，主要用于绑定事件
        super.onBindViewHolder(holder, position)

    }


    /**绑定下载事件*/
    private fun bindBookDownloadClickEvent(holder: ViewHolder, position: Int, bookDownload: BookDownload) {
        //下载状态
        val status = bookDownload.status
        //设置图标文件
        var icon = R.drawable.icon_play
        if(BookDownloadEnum.DOWNLOADING.equalsCode(status)){//下载中
            icon = R.drawable.icon_stop
        }else if(BookDownloadEnum.FINISH.equalsCode(status)){//已完成
            icon = R.drawable.icon_replay
        }
        holder.iconBookDownload.setImageDrawable(context.getDrawable(icon))
        val btnBookDownload = holder.btnBookDownload
        btnBookDownload.setOnClickListener{
            //获取状态
            val currentStatus = bookDownload.status

            //如果是已完成，清除下标，重新开始
            if(BookDownloadEnum.FINISH.equalsCode(currentStatus)){
                bookDownload.crawlerIndex = 0
            }

            //判断状态，是否需要下载
            if(BookDownloadEnum.DOWNLOADING.equalsCode(currentStatus)){//下载中
                //停止线程
                BookDownloadManager.getInstance().stopTask(bookDownload)
                //设置为暂停
                this.updateDownloadStatus(bookDownload, BookDownloadEnum.PAUSE.typeCode)
            }else{
                //开始下载
                BookDownloadManager.getInstance().startDownload(bookDownload)
            }
            //刷新列表项目
            refreshDownloadItem(position, bookDownload)
        }

    }

    /**更新下载状态*/
    private fun updateDownloadStatus(download: BookDownload, status: Int){
        download.status = status
        bookDownloadRepository.save(download)
    }

    /**列表项的点击事件*/
    override fun itemClickEvent(data: BookDownload) {
    }


    /**刷新列表数据*/
    fun refreshDownloadItem(position: Int, bookDownload: BookDownload){
        //直接整个对象更新
        list[position] = bookDownload
        //刷新适配器
//        notifyItemChanged(position)
        notifyItemRangeChanged(position, 1)
    }

}